import 'package:ecy_app_flutter/ecycommon/utils/EcyRandomUtil.dart';
import 'package:ecy_app_flutter/routes/blind_box/exchange_market/models/exchange_user_group.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import '../models/exchange_card.dart';
import '../service/exchange_service.dart';
import '../widgets/exchange_success_dialog.dart';

class EcyExchangeApplyPage extends StatefulWidget {
  
  const EcyExchangeApplyPage({
    super.key,
    ExchangeCard? card,
  });

  @override
  _EcyExchangeApplyPageState createState() => _EcyExchangeApplyPageState();
}

class _EcyExchangeApplyPageState extends State<EcyExchangeApplyPage> {
  final ExchangeService _exchangeService = ExchangeService();
  final List<ExchangeUserGroup> _myCards = [ExchangeUserGroup(userName: "userName", userAvatar: EcyRandomUtil.randomIconUrl(), 
    offerCards: [ExchangeCard(id: 0, name: "1", imageUrl: EcyRandomUtil.randomIconUrl(), expiryTime: null, owned: true)], 
    wantCards: [ExchangeCard(id: 1, name: "123", imageUrl: EcyRandomUtil.randomIconUrl(), expiryTime: null, owned: false),ExchangeCard(id: 2, name: "123", imageUrl: EcyRandomUtil.randomIconUrl(), expiryTime: null, owned: false)],
     canExchange: false),
     ExchangeUserGroup(userName: "userName", userAvatar: EcyRandomUtil.randomIconUrl(), 
    offerCards: [ExchangeCard(id: 0, name: "1", imageUrl: EcyRandomUtil.randomIconUrl(), expiryTime: null, owned: true)], 
    wantCards: [ExchangeCard(id: 1, name: "123", imageUrl: EcyRandomUtil.randomIconUrl(), expiryTime: null, owned: false),ExchangeCard(id: 2, name: "123", imageUrl: EcyRandomUtil.randomIconUrl(), expiryTime: null, owned: false)],
     canExchange: false)];
  final bool _isLoading = false;
  final ExchangeCard _selectedCard = ExchangeCard(id: 0, name: "123", imageUrl: EcyRandomUtil.randomIconUrl(), expiryTime: null, owned: true);

  @override
  void initState() {
    super.initState();
    // _loadMyCards();
  }

  // Future<void> _loadMyCards() async {
  //   setState(() => _isLoading = true);
  //   try {
  //     final cards = await _exchangeService.getMyExchangeCards();
  //     setState(() {
  //       _myCards = cards;
  //       _isLoading = false;
  //     });
  //   } catch (e) {
  //     print('Error loading my cards: $e');
  //   }
  // }

  // Future<void> _applyExchange() async {
  //   if (_selectedCard == null) return;

  //   try {
  //     final success = await _exchangeService.applyExchange(
  //       requestedCardId: widget.targetCard.id,
  //       offeredCardId: _selectedCard!.id,
  //     );

  //     if (success && mounted) {
  //       Navigator.of(context).pop(true);
  //     }
  //   } catch (e) {
  //     print('Error applying exchange: $e');
  //   }
  // }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        centerTitle: true,
        title: const Text('互换集市'),
        backgroundColor: Colors.white,
        foregroundColor: Colors.black,
        elevation: 0,
        leading: IconButton(
            icon: const Icon(Icons.arrow_back_ios, color: Colors.black),
            onPressed: () => Navigator.of(context).pop(),
          ),
      ),
      body: _isLoading
          ? const Center(child: CircularProgressIndicator())
          : Column(
              children: [
                Expanded(
                  child: Column(
                    children: [
                      SizedBox(height: 6),
                      _buildUserExchangeGroupOffer(_myCards[0], context),
                      SizedBox(height: 6),
                      _buildUserExchangeGroupWant(_myCards[1], context),
                    ],
                  ),
                ),
                SafeArea(
                  child: Padding(
                    padding: const EdgeInsets.all(16),
                    child: SizedBox(
                      width: double.infinity,
                      child: ElevatedButton(
                        onPressed: _selectedCard != null ? null : null,
                        style: ElevatedButton.styleFrom(
                          backgroundColor: Colors.pink,
                          padding: const EdgeInsets.symmetric(vertical: 16),
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(24),
                          ),
                        ),
                        child: const Text('确认交换'),
                      ),
                    ),
                  ),
                ),
              ],
            ),
    );
  }
} 
Widget _buildUserExchangeGroupOffer(ExchangeUserGroup group, BuildContext context) {
    return  Container(
      width: MediaQuery.of(context).size.width - 10 ,
    margin: EdgeInsets.zero,
    padding: EdgeInsets.all(16),
    decoration: BoxDecoration(
      color: Colors.white,
      borderRadius: BorderRadius.circular(12),
    ),
    child: Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        // 用户信息和按钮
        Row(
          children: [
            
            Text("我想换入", style: TextStyle(fontWeight: FontWeight.bold)),
            Spacer(),
            
          ],
        ),
        SizedBox(height: 12),
        // 卡片分栏
        Row(
          crossAxisAlignment: CrossAxisAlignment.start,
          
          children: [
            Column(
              children: [
                
                SizedBox(height: 4),
                Row(
                  children: group.offerCards.map((card) => _buildCardItem(card, owned: card.owned)).toList(),
                ),
              ],
            ),
            SizedBox(width: 32),
            
          ],
        ),
      ],
    ),
  );
  
}
Widget _buildUserExchangeGroupWant(ExchangeUserGroup group, BuildContext context) {
  return 
     Container(
      width: MediaQuery.of(context).size.width - 10 ,
    margin: EdgeInsets.zero,
    padding: EdgeInsets.all(16),
    decoration: BoxDecoration(
      color: Colors.white,
      borderRadius: BorderRadius.circular(12),
    ),
    child: Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        // 用户信息和按钮
        const Row(
          children: [
            
            Text("我想换出", style: TextStyle(fontWeight: FontWeight.bold)),
            Spacer(),
            
          ],
        ),
        const SizedBox(height: 12),
        // 卡片分栏
        Row(
          crossAxisAlignment: CrossAxisAlignment.start,
          
          children: [
            Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                SizedBox(height: 4),
                Row(
                  children: group.wantCards.map((card) => Padding(
                                                            padding: const EdgeInsets.only(right: 16.0),
                                                            child: _buildCardItem(card, owned: card.owned),
                                                          )
                                                        ).toList(),
                ),
              ],
            ),
          ],
        ),
      ],
    ),
  );
  
}

Widget _buildCardItem(ExchangeCard card, {bool owned = false}) {
  return Column(
    children: [
      // 卡片图片
      Stack(
        alignment: Alignment.center,
        children: [
          Image.network(card.imageUrl ?? EcyRandomUtil.randomIconUrl(), width: 50, height: 59),
      
          // if (!owned)
          //   Container(
          //     width: 60,
          //     height: 60,
          //     alignment: Alignment.center,
          //     child: Text('您暂未拥有', style: TextStyle(color: Colors.white, fontSize: 10)),
          //     decoration: BoxDecoration(
          //                   color: Colors.black.withOpacity(0.5),
          //                   borderRadius: BorderRadius.circular(4), // 圆角半径 12
          //               ),
          //   ),
        ]
      ),
      
        Text(card.name, style: TextStyle(fontSize: 12, color: Color(0xFF262626))),
    ],
  );
} 